#coding:utf-8

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from google.appengine.api import mail
import datetime
import Entities
import Contacts
import Relationships
import Activities
import logging


#Open the Index page (main/master page)
class IndexPage(webapp.RequestHandler):
    def get(self):
	
    	user = users.get_current_user()
	url = users.create_login_url(self.request.uri)
	url_linktext = 'Login'

	if user:
	    url = users.create_logout_url(self.request.uri)
	    url_linktext = 'Logout'

	values = {
	    'user': user,
	    'URL': url,
	    'URL_LinkText': url_linktext,
	}

	self.response.out.write(template.render('Index.html',values))


#ActivitiesPage
class ActivitiesPage(webapp.RequestHandler):
    def get(self):
	user = users.get_current_user()
	url = users.create_login_url(self.request.uri)
	url_linktext = 'Login'

	if user:
	    url = users.create_logout_url(self.request.uri)
	    url_linktext = 'Logout'
	
	listActivities = Activities.getActivities(user)
	NumberActivities = 0
	
	if listActivities:
	    NumberActivities = listActivities.count()

	ActivityID = self.request.get('id')
	EntityID = self.request.get('entityAbbr')
	
	logging.info('ActivityID = %s' %ActivityID)
	
	edActivity=None
	EditMode=0
	Action='/newactivity'
	matchEnt=''
	if ActivityID:
	    edActivity=Activities.getActivity(ActivityID, user)
	    EditMode=1
	    Action='/updateactivity?id='+ActivityID
	    matchEnt=edActivity.entityCode.key().id()

	# preenche a combo para as entidades
	beEntities = Entities.getEntities(user)
	listEntities = '<option></option>'
	if EntityID:
	    matchEnt=EntityID
	    
	if beEntities:
	    for CurrEntity in beEntities:
		if str(CurrEntity.key().id()) == str(matchEnt):
		    listEntities += '<option selected'
		else:
		    listEntities += '<option'
		listEntities += ' value="' + str(CurrEntity.key().id()) + '">' + CurrEntity.EntityAbbr + '</option>'

	# preenche a combo para os contactos
	listContacts = '<option></option>'
	if EntityID:
	    relEntCont=Relationships.getRelsEntityContact_ByEntity(EntityID,user)
	    for CurrContact in relEntCont:
		if EditMode == 1 and CurrContact.ContactRef.key().id() == edActivity.contact.key().id():
		    listContacts += '<option selected'
		else:
		    listContacts += '<option'
		listContacts += ' value="' + str(CurrContact.ContactRef.key().id()) + '">' + CurrContact.ContactRef.Name + '</option>'	    
	else:
	    beContacts = Contacts.getContacts(user)
	    if beContacts:
		for CurrContact in beContacts:
		    if EditMode == 1 and CurrContact.key().id() == edActivity.contact.key().id():
			listContacts += '<option selected'
		    else:
			listContacts += '<option'
		    listContacts += ' value="' + str(CurrContact.key().id()) + '">' + CurrContact.Name + '</option>'

	# preenche a combo para o tipo de actividade
	arrayTypeActivity = ['1.Email','2.Carta','3.Fax','4.Telefonema', '5.Reunião']
	listTypeActivity = ''
	for type in arrayTypeActivity[:]:
	    if EditMode == 1 and type[0] == edActivity.activity[0]:
		listTypeActivity += '<option selected>'
	    else:
		listTypeActivity += '<option>'
	    listTypeActivity += type + '</option>'

	# preenche a combo para o tipo de prioridade
	arrayPriority = ['1.Baixa','2.Média','3.Alta']
	listPriorities = ''
	for priority in arrayPriority[:]:
	    if EditMode == 1 and priority[0] == edActivity.priority[0]:
		listPriorities += '<option selected>'
	    else:
		listPriorities += '<option>'
	    listPriorities += priority + '</option>'

        values = {
            'Activities': listActivities,
            'listTypeActivity': listTypeActivity,
            'listEntities': listEntities,
            'listPriorities': listPriorities,
	    'listContacts': listContacts,
            'edActivity': edActivity,
            'NumberActivities' : NumberActivities,
            'EditMode' : EditMode,
            'Action':	Action,
            'user': user,
            'URL': url,
            'URL_LinkText': url_linktext}

	self.response.out.write(template.render('Activities.html', values))

#RoutesPage
class RoutesPage(webapp.RequestHandler):
    def get(self):
	user = users.get_current_user()
	url = users.create_login_url(self.request.uri)
	url_linktext = 'Login'

	if user:
	    url = users.create_logout_url(self.request.uri)
	    url_linktext = 'Logout'

	listActivities = Activities.getActivities(user)
	NumberActivities = 0
	
	if listActivities:
	    NumberActivities = listActivities.count()

	# preenche a combo para as entidades
	beEntities = Entities.getEntities(user)
	listEntities = '<option></option>'
	if beEntities:
	    for CurrEntity in beEntities:
		listEntities += '<option>'
		listEntities += CurrEntity.EntityAbbr + '</option>'

	# preenche a combo para os contactos
	listContacts = '<option></option>'
	beContacts = Contacts.getContacts(user)
	if beContacts:
	    for CurrContact in beContacts:
		listContacts += '<option>'
		listContacts += CurrContact.Name + '</option>'

	# preenche a combo para o tipo de actividade
	arrayTypeActivity = ['1.Email','2.Carta','3.Fax','4.Telefonema', '5.Reunião']
	listTypeActivity = '<option></option>'
	for type in arrayTypeActivity[:]:
	    listTypeActivity += '<option>'
	    listTypeActivity += type + '</option>'

	# preenche a combo para o tipo de prioridade
	arrayPriority = ['1.Baixa','2.Média','3.Alta']
	listPriorities = '<option></option>'
	for priority in arrayPriority[:]:
	    listPriorities += '<option>'
	    listPriorities += priority + '</option>'
	
	now = datetime.datetime.now()

	sinceDate = now.strftime("%d/%m/%Y")
	toDate = sinceDate
	
	values = {
	    'Activities': listActivities,
	    'listTypeActivity': listTypeActivity,
	    'listEntities': listEntities,
	    'listPriorities': listPriorities,
	    'listContacts': listContacts,
	    'NumberActivities' : NumberActivities,
	    'user': user,
	    'URL': url,
	    'URL_LinkText': url_linktext,
	    'sinceDate': sinceDate,
	    'toDate': toDate }

	self.response.out.write(template.render('Routes.html', values))

#UpdateRoutes
class UpdateRoutes(webapp.RequestHandler):
    def post(self):

	user = users.get_current_user()
	
	if user:
	    url = users.create_login_url(self.request.uri)
	    url_linktext = 'Login'

	    if user:
		url = users.create_logout_url(self.request.uri)
		url_linktext = 'Logout'

	    filterEntityCode = self.request.get('entityCode')
	    filterContact = self.request.get('contact')
	    filterActivity = self.request.get('activity')
	    filterPriority = self.request.get('priority')
	    sinceDate = self.request.get('sinceDate')
	    toDate = self.request.get('toDate');
	    
	    listActivities = Activities.getActivitiesFilter(
			user,
			filterEntityCode,
			filterContact,
			filterActivity,
			filterPriority,
			datetime.datetime.strptime(sinceDate, '%d/%m/%Y'),
			datetime.datetime.strptime(toDate, '%d/%m/%Y'))
	    NumberActivities = 0
	    
	    if listActivities:
		NumberActivities = listActivities.count()

	    # preenche a combo para as entidades
	    beEntities = Entities.getEntities(user)
	    listEntities = '<option></option>'
	    for CurrEntity in beEntities:
		if CurrEntity.EntityAbbr == filterEntityCode:
		    listEntities += '<option selected>'
		else:
		    listEntities += '<option>'
		listEntities += CurrEntity.EntityAbbr + '</option>'

	    # preenche a combo para os contactos
	    listContacts = '<option></option>'
	    beContacts = Contacts.getContacts(user)
	    if beContacts:
		for CurrContact in beContacts:
		    if CurrContact.Name == filterContact:
			listContacts += '<option selected>'
		    else:
			listContacts += '<option>'		    
		    listContacts += CurrContact.Name + '</option>'

	    # preenche a combo para o tipo de actividade
	    arrayTypeActivity = ['1.Email','2.Carta','3.Fax','4.Telefonema', '5.Reunião']
	    listTypeActivity = '<option></option>'
	    for type in arrayTypeActivity[:]:
		if filterActivity and type[0] == filterActivity[0]:
		    listTypeActivity += '<option selected>'
		else:
		    listTypeActivity += '<option>'		
		listTypeActivity += type + '</option>'

	    # preenche a combo para o tipo de prioridade
	    arrayPriority = ['1.Baixa','2.Média','3.Alta']
	    listPriorities = '<option></option>'
	    for priority in arrayPriority[:]:
		if filterPriority and priority[0] == filterPriority[0]:
		    listPriorities += '<option selected>'
		else:
		    listPriorities += '<option>'
		listPriorities += priority + '</option>'

	    values = {
		'Activities': listActivities,
		'listTypeActivity': listTypeActivity,
		'listEntities': listEntities,
		'listPriorities': listPriorities,
		'listContacts': listContacts,
		'NumberActivities' : NumberActivities,
		'user': user,
		'URL': url,
		'URL_LinkText': url_linktext,
		'sinceDate': sinceDate,
		'toDate': toDate }

	    self.response.out.write(template.render('Routes.html', values))


#EntitiesPage
class EntitiesPage(webapp.RequestHandler):
    def get(self):
	
    	user = users.get_current_user()
	url = users.create_login_url(self.request.uri)
	url_linktext = 'Login'

	if user:
	    url = users.create_logout_url(self.request.uri)
	    url_linktext = 'Logout'

	
	beEntities = Entities.getEntities(user)
	EntitiesCount=0
	if beEntities:
	    EntitiesCount=beEntities.count()
	
	EntityID = self.request.get('id')
	edEntity=None
	EditMode=0
	Action='/newentity'
	if EntityID:
	    edEntity=Entities.getEntity(EntityID, user)
	    EditMode=1
	    Action='/updateentity?id='+EntityID
	    

	values = {
	    'Entities': beEntities,
	    'edEntity': edEntity,
	    'EntitiesCount' : EntitiesCount,
	    'EditMode' : EditMode,
	    'Action':	Action,
	    'user': user,
	    'URL': url,
	    'URL_LinkText': url_linktext,
	}
	self.response.out.write(template.render('Entities.html', values))	
    


#ContactsPage
class ContactsPage(webapp.RequestHandler):
    def get(self):
	
    	user = users.get_current_user()
	url = users.create_login_url(self.request.uri)
	url_linktext = 'Login'

	if user:
	    url = users.create_logout_url(self.request.uri)
	    url_linktext = 'Logout'
	
	beContacts = Contacts.getContacts(user)
	ContactsCount=0
	if beContacts:
	    ContactsCount=beContacts.count()
	
	ContactID = self.request.get('id')
	edContact=None
	EditMode=0
	Action='/newcontact'
	if ContactID:
	    edContact=Contacts.getContact(ContactID, user)
	    EditMode=1
	    Action='/updatecontact?id='+ContactID
	    

	values = {
	    'Contacts': beContacts,
	    'edContact': edContact,
	    'ContactsCount' : ContactsCount,
	    'EditMode' : EditMode,
	    'Action':	Action,
	    'user': user,
	    'URL': url,
	    'URL_LinkText': url_linktext,
	}
	self.response.out.write(template.render('Contacts.html', values))	



#Entities/Contacts relationships page
class RelsEntityContactPage(webapp.RequestHandler):
    def get(self):
	
    	user = users.get_current_user()
	url = users.create_login_url(self.request.uri)
	url_linktext = 'Login'

	if user:
	    url = users.create_logout_url(self.request.uri)
	    url_linktext = 'Logout'
	
	RelEntID = self.request.get('ent_id')
	RelEntType = self.request.get('ent_type')
	
	logging.info('EntityType =:%s' %RelEntType)
	if (RelEntType=='Entity'):
	    beRels = Relationships.getRelsEntityContact_ByEntity (RelEntID, user)
	    RelEntCode=Entities.getEntity(RelEntID, user).EntityAbbr	    
	else:
	    beRels = Relationships.getRelsEntityContact_ByContact (RelEntID, user)
	    RelEntCode=Contacts.getContact(RelEntID, user).Name
	
	TargetEntitiesList=Entities.getEntities(user)
	TargetContactsList=Contacts.getContacts(user)
	
	logging.info('EntityCode = %s' %RelEntCode)
	
	RelsCount=0
	if beRels:
	    RelsCount=beRels.count()
	
	RelID = self.request.get('id')
	edRel=None
	EditMode=0	
	Action='/newrelationship?ent_id='+RelEntID+'&ent_type='+RelEntType
	if RelID:
	    edRel=Relationships.getRelEntityContact(RelID, user)
	    EditMode=1
	    Action='/updaterelationship?ent_id='+RelEntID+'&ent_type='+RelEntType+'&id='+RelID
	    

	values = {
	    'Relationships'		: beRels,
	    'edRelationship'		: edRel,
	    'RelationshipsCount' 	: RelsCount,
	    'RelEntityID' 		: RelEntID,
	    'RelEntityType' 		: RelEntType,
	    'RelEntityCode' 		: RelEntCode,
	    'TargetEntitiesList' 	: TargetEntitiesList,
	    'TargetContactsList' 	: TargetContactsList,
	    'EditMode' 			: EditMode,
	    'Action'			: Action,
	    'user'			: user,
	    'URL'			: url,
	    'URL_LinkText'		: url_linktext,
	}
	self.response.out.write(template.render('Relationships.html', values))	


# This class creates a new Activity item
class NewActivity(webapp.RequestHandler):
    def post(self):
	
	user = users.get_current_user()
	
	if user:
	    newActivity = Activities.addActivity(
		vAuthor = users.get_current_user(),
		vActivity = self.request.get('activity'),
		vPriority = self.request.get('priority'),
		vEntityCode = self.request.get('entityCode'),
		vContact = self.request.get('contact'),
		vShortDescription = self.request.get('shortDescription'),
		vLongDescription = self.request.get('longDescription'),
		vDueDate = datetime.datetime.strptime(self.request.get('dueDate'), '%d/%m/%Y'),
		vFinished = False,
		user = user
		)
	    self.redirect('/loadactivities')

# This class deletes the selected Activity
class DeleteActivity(webapp.RequestHandler):
    def get(self):
	user = users.get_current_user()
	if user:
	    ActivityID = self.request.get('id')
	    Activities.deleteActivity(ActivityID, user)
	    self.redirect('/loadactivities')

class UpdateActivity(webapp.RequestHandler):
    def post(self):
	
	user = users.get_current_user()
	if user:
	    ActivityID = self.request.get('id')	    
	    Activities.updateActivity(
		ActivityID	= ActivityID,
		vAuthor 	= user,
		vActivity 	= self.request.get('activity'),
		vPriority 	= self.request.get('priority'),
		vEntityCode 	= self.request.get('entityCode'),
		vContact 	= self.request.get('contact'),
		vShortDescription = self.request.get('shortDescription'),
		vLongDescription = self.request.get('longDescription'),
		vDueDate 	= datetime.datetime.strptime(self.request.get('dueDate'), '%d/%m/%Y'),
		vFinished 	= False,
		user		= user
		)

	    self.redirect('/loadactivities')
	    

# Para marcar uma actividade como fechada
class DoneActivity(webapp.RequestHandler):
    def get(self):
	user = users.get_current_user()
	if user:
	    ActivityID = self.request.get('id')
	    Activities.doneActivity(ActivityID, user)
	    self.redirect('/loadactivities')
	    


# This class creates a new Entity item
class NewEntity(webapp.RequestHandler):
    def post(self):
	
	user = users.get_current_user()
	
	if user:
	    testurl = self.request.get('url')
	    if not testurl.startswith("http://") and testurl:
		testurl = "http://"+ testurl
	    newEntity = Entities.addEntity(
		vEntityAbbr 	= self.request.get('EntityAbbr'), 
		vEntityName 	= self.request.get('EntityName'),
		vAddress1  	= self.request.get('Address1'),
		vAddress2	= self.request.get('Address2'),
		vPostalCode	= self.request.get('PostalCode'),
		vCity		= self.request.get('City'),
		vPhone		= self.request.get('Phone'),
		vFax		= self.request.get('Fax'),
		vEmail		= self.request.get('Email'),
		vURL		= self.request.get('URL'),
		vLatLng		= self.request.get('LatLng'), 
		vResponsible	= user,
		user		= user
		)

	    self.redirect('/loadentities')



# This class deletes the selected Entity
class DeleteEntity(webapp.RequestHandler):
    def get(self):
	user = users.get_current_user()
	if user:
	    EntityID = self.request.get('id')
	    Entities.deleteEntity(EntityID, user)
	    self.redirect('/loadentities')



class UpdateEntity(webapp.RequestHandler):
    def post(self):
	
	user = users.get_current_user()
	
	if user:
	    testurl = self.request.get('url')
	    if not testurl.startswith("http://") and testurl:
		testurl = "http://"+ testurl		
	    EntityID = self.request.get('id')	    
	    Entities.updateEntity(
		EntityID	= EntityID,
		vEntityAbbr 	= self.request.get('EntityAbbr'), 
		vEntityName 	= self.request.get('EntityName'),
		vAddress1  	= self.request.get('Address1'),
		vAddress2	= self.request.get('Address2'),
		vPostalCode	= self.request.get('PostalCode'),
		vCity		= self.request.get('City'),
		vPhone		= self.request.get('Phone'),
		vFax		= self.request.get('Fax'),
		vEmail		= self.request.get('Email'),
		vURL		= self.request.get('URL'),
		vLatLng		= self.request.get('LatLng'), 
		vResponsible	= user,
		user		= user
		)

	    self.redirect('/loadentities')
	    


# This class creates a new Contact item
class NewContact(webapp.RequestHandler):
    def post(self):
	
	user = users.get_current_user()
	
	if user:
	    testurl = self.request.get('url')
	    if not testurl.startswith("http://") and testurl:
		testurl = "http://"+ testurl
	    newContact = Contacts.addContact(
		vTitle 		= self.request.get('Title'), 
		vName 		= self.request.get('Name'),
		vBirthDate  	= datetime.datetime.strptime(self.request.get('BirthDate'), '%d/%m/%Y'),
		vMobilePhone	= self.request.get('MobilePhone'),
		vEmail		= self.request.get('Email'),
		user		= user
		)

	    self.redirect('/loadcontacts')



# This class deletes the selected Contact
class DeleteContact(webapp.RequestHandler):
    def get(self):
	user = users.get_current_user()
	if user:
	    ContactID = self.request.get('id')
	    Contacts.deleteContact(ContactID, user)
	    self.redirect('/loadcontacts')



class UpdateContact(webapp.RequestHandler):
    def post(self):
	
	user = users.get_current_user()
	
	if user:
	    testurl = self.request.get('url')
	    if not testurl.startswith("http://") and testurl:
		testurl = "http://"+ testurl		
	    ContactID = self.request.get('id')	    
	    Contacts.updateContact(
		ContactID	= ContactID,
		vTitle 		= self.request.get('Title'), 
		vName 		= self.request.get('Name'),
		vBirthDate  	= datetime.datetime.strptime(self.request.get('BirthDate'), '%d/%m/%Y'),
		vMobilePhone	= self.request.get('MobilePhone'),
		vEmail		= self.request.get('Email'),
		user		= user
		)

	    self.redirect('/loadcontacts')



# This class creates a new Relationship item
class NewRelationship(webapp.RequestHandler):
    def post(self):
	
	user = users.get_current_user()
	
	if user:
	    testurl = self.request.get('url')
	    if not testurl.startswith("http://") and testurl:
		testurl = "http://"+ testurl
		
	    RelEntID = self.request.get('ent_id')
	    RelEntType = self.request.get('ent_type')
	    
	    newRelationship = Relationships.addRelEntityContact(
		vEntityID 	= self.request.get('EntityID'), 
		vContactID 	= self.request.get('ContactID'),
		vJobTitle  	= self.request.get('JobTitle'),
		vJobEmail	= self.request.get('JobEmail'),
		vJobPhone	= self.request.get('JobPhone'),
	    	vJobMobile	= self.request.get('JobMobile'),
		user		= user
		)

	    self.redirect('/loadrelationships?ent_id='+RelEntID+'&ent_type='+RelEntType)



# This class deletes the selected Relationship
class DeleteRelationship(webapp.RequestHandler):
    def get(self):
	user = users.get_current_user()
	if user:
	    
	    RelEntID = self.request.get('ent_id')
	    RelEntType = self.request.get('ent_type')
	    
	    RelationshipID = self.request.get('id')
	    Relationships.deleteRelEntityContact(RelationshipID, user)
	    self.redirect('/loadrelationships?ent_id='+RelEntID+'&ent_type='+RelEntType)



class UpdateRelationship(webapp.RequestHandler):
    def post(self):
	
	user = users.get_current_user()
	
	if user:
	    testurl = self.request.get('url')
	    if not testurl.startswith("http://") and testurl:
		testurl = "http://"+ testurl
		
	    RelEntID = self.request.get('ent_id')
	    RelEntType = self.request.get('ent_type')
	    
	    RelationshipID = self.request.get('id')	    
	    Relationships.updateRelEntityContact(
		RelEntityContactID	= RelationshipID,
		vEntityID 		= self.request.get('EntityID'), 
		vContactID 		= self.request.get('ContactID'),
		vJobTitle  		= self.request.get('JobTitle'),
		vJobEmail		= self.request.get('JobEmail'),
		vJobPhone		= self.request.get('JobPhone'),
	    	vJobMobile		= self.request.get('JobMobile'),
		user			= user
		)

	    self.redirect('/loadrelationships?ent_id='+RelEntID+'&ent_type='+RelEntType)



# Register the URL with the responsible classes
application = webapp.WSGIApplication(
    [('/', IndexPage),
	('/newentity', NewEntity),
	('/updateentity', UpdateEntity),
	('/deleteentity', DeleteEntity),
	('/loadentities', EntitiesPage),
	('/newcontact', NewContact),
	('/updatecontact', UpdateContact),
	('/deletecontact', DeleteContact),
	('/loadcontacts', ContactsPage),	
	('/newrelationship', NewRelationship),
	('/updaterelationship', UpdateRelationship),
	('/deleterelationship', DeleteRelationship),
	('/loadrelationships', RelsEntityContactPage),
	('/newactivity', NewActivity),
	('/updateactivity', UpdateActivity),
	('/deleteactivity', DeleteActivity),
	('/loadactivities', ActivitiesPage),
	('/doneActivity', DoneActivity),
	('/loadroutes', RoutesPage),
	('/updateroutes', UpdateRoutes)
	],
    debug=True)



# Register the wsgi application to run
def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()